#!/usr/bin/python
# -*- coding=utf-8 -*-

import MySQLdb
import warnings
import datetime
import sys
import json
reload(sys)
sys.setdefaultencoding('utf8')
 
warnings.filterwarnings("ignore")
 
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
 
def getDB(dbConfigName):
    try:
        conn = MySQLdb.connect(host=dbConfig['host'], user=dbConfig['user'], passwd=dbConfig['passwd'],
                               port=dbConfig['port'])
        conn.autocommit(True)
        curr = conn.cursor()
        curr.execute("SET NAMES utf8");
        curr.execute("USE %s" % dbConfig['db']);
 
        return conn, curr
    except MySQLdb.Error, e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])
        return None, None
 
def mysql2json(dbConfigName, selectSql, jsonPath, fileName):
    conn, curr = getDB(dbConfigName)
    curr.execute(selectSql)
    datas = curr.fetchall()
    fields = curr.description
 
    column_list = []
    for field in fields:
        column_list.append(field[0])
 
    with open('{jsonPath}{fileName}.json'.format(jsonPath=jsonPath, fileName=fileName), 'a+') as f:
        for row in datas:
            result = {}
            for fieldIndex in range(0, len(column_list)):
                result[column_list[fieldIndex]] = str(row[fieldIndex])
            jsondata=json.dumps(result, ensure_ascii=False)
            f.write(jsondata + '\n')
    f.close()
 
    curr.close()
    conn.close()

def get256():
    '''
    256循环
    '''
    list_256 = []
    original_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    for i in original_list:
        for j in original_list:
            list_256.append(i+j)
    return list_256

def get4096():
    '''
    4096循环
    '''
    list_4096 = []
    list_256 = get256()
    original_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']

    for i in original_list:
        for j in list_256:
            list_4096.append(i+j)
    return list_4096
 
mysqlDb_config = {
    'host': '192.168.170.4',
    'user': 'root',
    'passwd': 'c4xRVCY2uECX1XAqcJyQy',
    'port': 3306
}

dbConfigName = 'mysqlDb_config'
dbConfig = eval(dbConfigName)
db = "fl_ly_energy"
table = "t_energy_system_billing"

range_list_4096 = []
range_list_4096 = get4096()
for i in range_list_4096:
    final_db = db + "_" + i[0:1]
    final_table = table + "_" + i

    dbConfig['db'] = final_db

    # Batch Test
    selectSql = "SELECT * FROM %s.%s;" % (final_db, final_table)
    jsonPath = '/home/webadmin/'
    fileName = table
    mysql2json(dbConfigName, selectSql, jsonPath, fileName)
